//
//  CZComposeTextView+Extension.swift
//  weiBo
//
//  Created by apple on 16/5/23.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

extension CZComposeTextView {
    
    var emotionText: String {
        var result = ""
        //在指定范围内 遍历副文本属性
        self.attributedText.enumerateAttributesInRange(NSMakeRange(0, self.attributedText.length), options: []) { (infoDic, range, _) -> Void in
            if let attachment = infoDic["NSAttachment"] as? CZTextAttachment {
                let chs = attachment.emotions?.chs!
                
                result += chs!
            }else {
                let text = self.attributedText.attributedSubstringFromRange(range).string
                result += text
            }
            
            
        }
        return result
    }
    
    

    func insertEmoticon(emotion: CZEmoticon) {
        //记录上一次的文本
        var originalAttr = NSMutableAttributedString(attributedString: self.attributedText)
        
        if emotion.type == "0" {
            //1.根据图片名字  创建一个UIImage
            let image = UIImage(named: emotion.path!)
            //2.根据图片创建一个文件副本( NSTextAttachment )
            let attachment = CZTextAttachment()
            attachment.emotions = emotion
            attachment.image = image
            //解决图片大小问题
            //获取文字的大小
            let fontHeight = self.font?.lineHeight
            attachment.bounds = CGRectMake(0, -4, fontHeight!, fontHeight!)
            
            //3 根据文本附件 创建一个副文本 NSAttributedString
            let attr = NSAttributedString(attachment: attachment)
            
            //  获取textview的选中范围
            var range = self.selectedRange
            //  替换选中的字符串
            originalAttr.replaceCharactersInRange(range, withAttributedString: attr)
            
            //  设置富文本的字体大小
            originalAttr.addAttribute(NSFontAttributeName, value: self.font!, range: NSMakeRange(0, originalAttr.length))
            
            //  设置富文本
            self.attributedText = originalAttr
            //  每次点击表情开始位置加一
            range.location += 1
            //  设置选中范围长度为0
            range.length = 0
            //  设置选中范围
            self.selectedRange = range
            
            //  发送文字改变的通知
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            //  自动使用代理调用代理方法 ? 意思判断这个可选方法是否现实
            self.delegate?.textViewDidChange?(self)

            
        }else {
            //将emoji变为emoji字符串
            
            self.insertText((emotion.code! as NSString).emoji())
        }
        
        
        
    }
    



}
